package com.student.liu.holder;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 上下文持有对象
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据名称获取bean
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T>T getBean(String beanName){
        return (T)applicationContext.getBean(beanName);
    }

    /**
     * 根据类型获取bean
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T>T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }
}
